// ==UserScript==
// @name           SCB EASY NET Historical Statement CSV
// @namespace      pybt
// @include        https://www.scbeasy.com/v1.4/site/th/acc/acc_bnk_pst.asp
// ==/UserScript==

// Add jQuery
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);

// Check if jQuery's loaded
function GM_wait() {
  if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait, 100); }
  else { $ = unsafeWindow.jQuery; letsJQuery(); }
}
GM_wait();

// All your GM code must be inside this function
function letsJQuery() {

  var u = function(msg) {
    $("#csv").append(msg);
  }

  var bd = $("body");
  var html = "";
  html += '<div style="clear: both;"></div>'; 
  html += '<h2 style="background-color:yellow;text-align:center;">CSV</h2>'; 
  html += '<pre id="csv" style="border: 1px dotted;padding: 5px 5px 5px 5px;margin: 5px 5px 5px 5px;"></pre>';
  bd.append(html);

  $.ajaxSetup({
      'beforeSend' : function(xhr) {
      xhr.overrideMimeType('text/html; charset=windows-874');
      },
      });

  $("#Select_Month > option").each(function(i, e){ 

      $("#Select_Month").val($(e).val());
      $.post('acc_bnk_pst.asp', $("#AccountInfo_form").serialize(), function(data){

        var tables = $("table", data);
        var h_table = $(tables.get(18));
        var h_row = $("tr:gt(0)", h_table);
        h_row.each(function(i, h_row_e){

          if(i < h_row.length - 1) {
          var tmp = $("td", h_row_e).length;
          $("td", h_row_e).each(function(i, h_cell_e) {

            var text = $(h_cell_e).text();
            text = '"' + text.trim() + '"';
            u(text);
            if(i != tmp - 1){
            u(",");
            }
            });
          u("\n");
          }
          });
      });
  });
}
